<template>
  <div class="flex-grow-1 container-p-y"  :class="[layout]">
    <el-card>
      <div class="search-hide">
        <a v-on:click="searchShow = !searchShow">
          <i :class="searchShow ? 'el-icon-arrow-up' : 'el-icon-search'"></i>
        </a>
      </div>
      <div class="filter-area" v-if="searchShow">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" label-position="left">
          <el-form-item :label="$t('rent.platform')" prop="platform">
              <el-input v-model="queryParams.platform" :placeholder="$t('plc.iplatform')" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item :label="$t('rent.mail')" prop="email">
              <el-input v-model="queryParams.email" :placeholder="$t('plc.mail')" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item :label="$t('rent.type')" prop="type">
              <el-select :popper-append-to-body="false" :placeholder="$t('plc.type')" v-model="queryParams.type" @change="handleTypeChange()"
                clearable size="small">
                <el-option v-for="item in chargeTypeList" :key="item.val" :label="item.text" :value="item.val" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('rent.orderid')" prop="orderid">
              <el-input v-model="queryParams.orderid" :placeholder="$t('plc.orderid')" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item :label="$t('rent.owner')" prop="createBy" v-hasPermi="['bonus:charge:edit']">
              <el-input v-model="queryParams.createBy" :placeholder="$t('plc.owner')" clearable size="small"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item :label="$t('rent.CREATETIME')" prop="createTime">
              <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange" range-separator="-" :start-placeholder="$t('plc.timestart')"
                :end-placeholder="$t('plc.timeend')"></el-date-picker>
            </el-form-item>
          <el-form-item class="flex flex-end">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('btn.search')}}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('btn.reset')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-row :gutter="5" class="mb8" v-if="false">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['bonus:charge:add']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['bonus:charge:edit']">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['bonus:charge:remove']">删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['bonus:charge:export']">导出
          </el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="chargeList" @sort-change="handleSortChange"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60" fixed="left" align="center" />
        <el-table-column label="ID" align="center" prop="id" v-if="false" />
        <el-table-column :label="$t('rent.orderid')" align="center" prop="orderid" width="165" />
        <el-table-column :label="$t('rent.type')" width="140px" align="center" prop="type">
          <template slot-scope="scope">
            <span>{{ parseChargeType(scope.row.type) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.email')" width="290px" align="center" prop="order.email" />
        <el-table-column :label="$t('rent.platform')" align="center" width="140px" prop="order.platform" >
          <template slot-scope="scope">
            <span class="row-sp-has-img" v-html="platformFormat(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.changed')" width="140px" align="right" prop="balanceChanged">
          <template slot-scope="scope">
            <span :class="{'rnt-bon-r':scope.row.balanceChanged<0,'rnt-bon-g':scope.row.balanceChanged>0}">{{scope.row.balanceChanged}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.oldbalance')" align="right" width="140px" prop="oldBalance" />
        <el-table-column :label="$t('rent.balance')"  width="140px" align="right" prop="balance" />
        <el-table-column :label="$t('rent.owner')" align="center"  width="200px" prop="createBy" />
        <el-table-column :label="$t('rent.CREATETIME')" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.action')" fixed="right" align="center" width="100px">
          <template slot-scope="scope">
            <el-popover trigger="click">
              <div class="flex-c-btns">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['bonus:charge:edit']"></el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['bonus:charge:remove']"></el-button>
              </div>
              <a slot="reference"><i class="ti ti-dots-vertical g-row-opt"></i></a>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>

    <Footer :layout="layout"/>
    <!-- 添加或修改Bonus Charge对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" :width="dialogWidth" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="balanceAfter" prop="balanceChanged">
          <el-input v-model="form.balanceChanged" placeholder="balanceAfter" />
        </el-form-item>
        <el-form-item label="Bonus Changed" prop="balance">
          <el-input v-model="form.balance" placeholder="Bonus Changed" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="Bonus Charge" :visible.sync="showDrawer" :size="drawerWidth" :with-header="false">
      <el-row :gutter="5" style="display: block;padding: 10px 10px 10px 20px">
        <el-button :disabled="showDrawerIndex === 1" icon="el-icon-d-arrow-left" type="primary" size="mini"
          @click="handlePrevRowClick"></el-button>
        <span style="padding:0 5px;">{{ showDrawerIndex }}（第{{ queryParams.pageNum }}页）</span>
        <el-button :disabled="showDrawerIndex === chargeList.length" icon="el-icon-d-arrow-right" type="primary"
          size="mini" @click="handleNextRowClick"></el-button>
      </el-row>
      <div :style="drawerStyle">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="balanceAfter" prop="balanceChanged">
            <el-input v-model="form.balanceChanged" readonly />
          </el-form-item>
          <el-form-item label="Bonus Changed" prop="balance">
            <el-input v-model="form.balance" readonly />
          </el-form-item>
          <el-form-item label="Owner" prop="createBy">
            <el-input v-model="form.createBy" readonly />
          </el-form-item>
          <el-form-item label="Create Time" prop="createTime">
            <span>{{ parseTime(form.createTime, '{y}-{m}-{d}') }}</span>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listType } from "@/api/mail/type";
import { listTypeplatform } from "@/api/mail/typeplatform";
import Footer from '../../../components/Footer'
import { listCharge, getCharge, delCharge, addCharge, updateCharge, exportCharge } from "@/api/bonus/charge";

export default {
  name: "Charge",
  data() {
    return {
      allmailPlatformList:[],
      // 显示搜索区域
      searchShow: true,
      // 显示drawer相关设置
      showDrawer: false,
      drawerWidth: document.documentElement.clientWidth < 800 ? "72%" : "67%",
      showDrawerIndex: 0,
      drawerStyle: 'overflow-y: scroll;padding: 10px;height: ' + (document.documentElement.clientHeight - 80) + 'px;',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // dialogWidth
      dialogWidth: document.documentElement.clientWidth < 800 ? "320px" : "500px",
      // 总条数
      total: 0,
      // Bonus Charge表格数据
      chargeList: [],
      chargeTypeList: [
        { 'text': 'MailFee', val: 0 },
        { 'text': 'Refund', val: 1 },
        { 'text': 'Charge', val: 2 },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        platform: null,
        email: null,
        orderid: null,
        type: null,
        createBy: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  components:{Footer},
  computed: {
    layout(){
      return localStorage.getItem('v-layout-content')||'container-xxl';
    }
  },
  async mounted(){
    let param = { pageNum: 1, pageSize: 1000 }
    let res=await listType(param);

    let _allPls=[];
    
    let promises=[];
    
    res.rows.filter((item)=>{
      let param = { pageNum: 1, pageSize: 9999, mailTypeCode: item.mailTypeCode }
      promises.push(listTypeplatform(param));
    })
    let allres=await Promise.all(promises);
    allres.map(_res=>{
      _allPls=[..._allPls,..._res.rows];
    })
    this.allmailPlatformList = _allPls;
  },
  created() {
    window.addEventListener('resize', this.handleResize)
    this.getList();
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // Platform字典翻译
    platformFormat(row, column) {
      let item=this.allmailPlatformList.filter(r=>{
        if(!row.order)row.order={}
        return r.platformCode == row.order.platform;
      });
      if(item.length>0)
        return '<img class="row-img-icon" src="'+item[0].icon+'"/>'+item[0].platformName;
      else
        return ''
      //return this.selectDictLabel(this.platformOptions, row.platform);
    },
    /** 查询Bonus Charge列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.orderByColumn == null) {
        this.queryParams.orderByColumn = 'createTime'
        this.queryParams.isAsc = 'desc'
      }

      listCharge(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.chargeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        balanceChanged: null,
        orderid: null,
        oldBalance: null,
        balance: null,
        createBy: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleTypeChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handlePrevRowClick() {
      --this.showDrawerIndex
      this.form = this.chargeList[this.showDrawerIndex - 1];
    },
    handleNextRowClick() {
      ++this.showDrawerIndex
      if (this.chargeList.length >= this.showDrawerIndex) {
        this.form = this.chargeList[this.showDrawerIndex - 1];
      }
    },
    handleShowDetailClick(row, index) {
      this.showDrawerIndex = 1 + index
      this.form = row;
      this.showDrawer = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Bonus Charge";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCharge(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改Bonus Charge";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCharge(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCharge(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除Bonus Charge编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delCharge(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有Bonus Charge数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportCharge(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function () {
      });
    },
    /** 弹出对话框的屏幕适应 */
    handleResize(event) {
      if (this.dialogWidth === '500px') {
        if (document.body.clientWidth < 800) {
          this.dialogWidth = "320px"
        }
      } else if (document.body.clientWidth >= 800) {
        this.dialogWidth = '500px'
      }
    },
    handleSortChange(e) {
      if (e.order === "descending") {
        this.queryParams.orderByColumn = e.prop
        this.queryParams.isAsc = 'desc'
      } else if (e.order === "ascending") {
        this.queryParams.orderByColumn = e.prop
        this.queryParams.isAsc = 'asc'
      } else {
        this.queryParams.orderByColumn = 'createTime'
        this.queryParams.isAsc = 'desc'
      }
      this.getList()
    },
    parseChargeType(val) {
      for (let i = 0; i < this.chargeTypeList.length; i++) {
        if (this.chargeTypeList[i].val == val) return this.chargeTypeList[i].text;
      }
      return val;
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 20px 20px 5px 20px;
  border-style: solid;
  border-width: 0px 0 2px 0;
  border-color: whitesmoke;
}

::v-deep .el-dialog__footer {
  padding: 12px 20px;
}

@media (max-width: 480px) {
  ::v-deep .el-dialog__body {
    padding: 20px 20px 5px 20px;
    border-style: solid;
    border-width: 0px 0 2px 0;
    border-color: whitesmoke;
  }

  ::v-deep .el-dialog__footer {
    padding: 12px 20px;
  }

  ::v-deep .el-pagination__sizes {
    margin: 0;
  }

  ::v-deep .el-pagination .el-select .el-input {
    width: 85px;
    margin: 0;
  }

  ::v-deep .el-pagination__total {
    margin-right: 2px;
  }

  ::v-deep .el-pagination__jump {
    display: none !important;
  }
}
</style>
